package common

import (
	"crypto/md5"
	"fmt"
	"io"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"time"
)

type stringCommon struct {
}

var String stringCommon

const TIME_LAYOUT = "2006-01-02 15:04:05"

func (stringCommon) VerifyEmailFormat(email string) bool {
	pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` //匹配电子邮箱
	reg := regexp.MustCompile(pattern)
	return reg.MatchString(email)
}

func (stringCommon) Md5(str string) string {
	w := md5.New()
	io.WriteString(w, str)
	//将str写入到w中
	md5str2 := fmt.Sprintf("%x", w.Sum(nil))
	return md5str2
}

func (stringCommon) Trim(s string) string {

	return strings.TrimSpace(s)
}

func (common stringCommon) ToTime(s string) time.Time {
	tempTIme, err := time.ParseInLocation(TIME_LAYOUT, common.Trim(s), time.Local)
	if err != nil {
		return time.Time{}
	}
	return tempTIme
}

func (stringCommon) toInt(s string) (int, error) {
	return strconv.Atoi(s)

}

func (common stringCommon) ToIntDefault(s string, defaultValue int) int {
	v, err := common.toInt(s)
	if err != nil {
		return defaultValue
	}
	return v
}

func (stringCommon) Split(s string, split string) []string {
	return strings.Split(s, split)
}
func (common stringCommon) SplitToString(s string, split string, join string) string {
	return strings.Join(common.Split(s, split), join)
}

func (common stringCommon) ToInt(s string) int {
	v, _ := common.toInt(s)
	return v
}

// InArray 查找字符是否在数组中
func (stringCommon) InArray(obj interface{}, target interface{}) bool {
	targetValue := reflect.ValueOf(target)
	switch reflect.TypeOf(target).Kind() {
	case reflect.Slice, reflect.Array:
		for i := 0; i < targetValue.Len(); i++ {
			if targetValue.Index(i).Interface() == obj {
				return true
			}
		}
	case reflect.Map:
		if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
			return true
		}
	}

	return false
}
func (stringCommon) TimeDiffDay(t1, t2 time.Time) int {

	t1 = time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, time.Local)
	t2 = time.Date(t2.Year(), t2.Month(), t2.Day(), 0, 0, 0, 0, time.Local)

	return int(t1.Sub(t2).Hours() / 24)

}

func (stringCommon) CompressStr(str string) string {
	if str == "" {
		return ""
	}
	//匹配一个或多个空白符的正则表达式
	reg := regexp.MustCompile("\\s+")
	return reg.ReplaceAllString(str, "")
}

func deleteExtraSpace(s string) string {
	//删除字符串中的多余空格，有多个空格时，仅保留一个空格
	s1 := strings.Replace(s, "  ", " ", -1)      //替换tab为空格
	regstr := "\\s{2,}"                          //两个及两个以上空格的正则表达式
	reg, _ := regexp.Compile(regstr)             //编译正则表达式
	s2 := make([]byte, len(s1))                  //定义字符数组切片
	copy(s2, s1)                                 //将字符串复制到切片
	spc_index := reg.FindStringIndex(string(s2)) //在字符串中搜索
	for len(spc_index) > 0 {                     //找到适配项
		s2 = append(s2[:spc_index[0]+1], s2[spc_index[1]:]...) //删除多余空格
		spc_index = reg.FindStringIndex(string(s2))            //继续在字符串中搜索
	}
	return string(s2)
}
